import { createRouter, createWebHashHistory } from 'vue-router'
import LayOut from '../views/LayOut/LayOut'
import store from "../store/index.js"
import { notification } from 'ant-design-vue';

const routes = [
  // 根路径重定向到登录页
  {
    path: '/',
    redirect: '/user/login'
  },
  //登录
  {
    path: "/user/login",
    name: "login",
    component: () => import("../views/pages/login.vue")
  },
  //各个pages
  {
    path: "/main",
    name: "layout",
    component: LayOut,
    //子路由
    children: [
      {
        path: '/index',
        name: 'index',
        component: () => import("../views/pages/rolesList.vue")
      },
      {
        path: '/user',
        name: 'user',
        component: () => import("../views/pages/usersList.vue")
      },
      {
        path: '/submitChargeRequest',
        name: 'submitChargeRequest',
        component: () => import("../views/pages/submitChargeRequest.vue")
      },
      {
        path: '/modifyAmount',
        name: 'modifyAmount',
        component: () => import("../views/pages/modifyAmount.vue")
      },
      {
        path: '/chMode',
        name: 'chMode',
        component: () => import("../views/pages/chMode.vue")
      },
      {
        path: '/startCharging',
        name: 'startCharging',
        component: () => import("../views/pages/startCharging.vue")
      },
      {
        path: '/stopCharging',
        name: 'stopCharging',
        component: () => import("../views/pages/stopCharging.vue")
      },
      {
        path: '/queue',
        name: 'queueInfo',
        component: () => import("../views/pages/queueInfo.vue")
      },
      {
        path: '/checkBill',
        name: 'checkBill',
        component: () => import("../views/pages/checkBill.vue")
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫：未登录强制跳转登录页
router.beforeEach((to, from, next) => {
  // 允许直接访问登录页
  if (to.path === '/user/login') {
    next();
    return;
  }
  // 判断登录状态（以 car_id 为准，优先 localStorage）
  const carId = localStorage.getItem('car_id') || sessionStorage.getItem('car_id');
  if (!carId) {
    next('/user/login');
  } else {
    next();
  }
});

export default router
